package com.huiyin.ui.shoppingcar;

import android.app.Activity;
import android.app.Dialog;
import android.content.Intent;
import android.os.Bundle;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.EditText;
import android.widget.LinearLayout;
import android.widget.TextView;

import com.google.gson.Gson;
import com.huiyin.AppContext;
import com.huiyin.R;
import com.huiyin.UIHelper;
import com.huiyin.UserInfo;
import com.huiyin.api.CustomResponseHandler;
import com.huiyin.api.RequstClient;
import com.huiyin.base.BaseActivity;
import com.huiyin.bean.BaseBean;
import com.huiyin.ui.servicecard.RechargeServiceCard;
import com.huiyin.utils.AppManager;
import com.huiyin.utils.BaseHelper;
import com.huiyin.utils.JSONParseUtils;
import com.huiyin.utils.MathUtil;
import com.huiyin.utils.StringUtils;
import com.pingplusplus.android.PaymentActivity;

/**
 * 选择支付方式页面
 * @author zhyao
 *
 */
public class CommitOrderActivityNew extends BaseActivity implements OnClickListener{
	
	private static final String TAG = "CommitOrderActivityNew";
	
	/**订单ID**/
	public static final String INTENT_KEY_ORDER_ID = "orderID";
	
	/**订单编号**/
	public static final String INTENT_KEY_ORDER_NUM = "orderNum";
	
	/**订单金额**/
	public static final String INTENT_KEY_ORDER_PRICE = "orderPrice";
	
	/**订单便民服务卡支付优惠价格**/
	public static final String INTENT_KEY_ORDER_SERVICE_CARD_PRICE = "orderServiceCardPrice";
	
	/**请求code**/
	private static final int REQUEST_CODE_PAYMENT = 1;
	
	/**支付渠道：支付宝 12**/
	private static final String CHANNEL_PAYWAY_ALIPAY = "12";
	
	/**支付渠道：微信 31**/
	private static final String CHANNEL_PAYWAY_WX = "31";
	
	/**支付渠道：银联 22**/
	private static final String CHANNEL_PAYWAY_YL = "22";
	
	/**支付方式：便民服务卡 1**/
	public static final int PAYWAY_SERVICE_CARD = 1;
	
	/**支付方式：支付宝 2**/
	public static final int PAYWAY_ALIPAY = 2;
	
	/**支付方式：微信 3**/
	public static final int PAYWAY_WX = 3;
	
	/**支付方式：银联 4**/
	public static final int PAYWAY_YL = 4;
	
	/**当前支付方式**/
	private int mCurPayWay;
	
	/**订单ID**/
	private String mOrderId;
	
	/**订单编号**/
	private String mOrderNum;
	
	/**订单金额**/
	private float mOrderPrice;
	
	/**订单便民服务卡支付优惠价格(可能没有)**/
	private float mOrderServiceCardPrice;
	
	/**导航左侧按钮**/
	private TextView mLeftTv;
	
	/**导航中间标题**/
	private TextView mMiddleTitleTv;
	
	/**导航右侧按钮**/
	private TextView mRightTv;
	
	/**订单价格**/
	private TextView mPayOrderPriceTv;
	
	/**订单编号**/
	private TextView mPayOrderNumTv;
	
	/**便民卡支付方式**/
	private LinearLayout mPaywayServiceCardLayout;
	
	/**支付宝支付方式**/
	private LinearLayout mPaywayAlipayLayout;
	
	/**微信支付方式**/
	private LinearLayout mPaywayWXLayout;
	
	/**银联支付方式**/
	private LinearLayout mPaywayYLLayout;
	
	/**便民卡支付信息**/
	private TextView mServiceCardInfoTv;
	
	/**便民服务卡支付对话框**/
	private Dialog mServiceCardDialog;
	
	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		
		setContentView(R.layout.shopping_commit_order);
		
		initData();
		initView();
	}
	
//	@Override
//	protected void onNewIntent(Intent intent) {
//		super.onNewIntent(intent);
//		
//		setIntent(intent);
//		
//		initData();
//		initView();
//	}
	
	/**
	 * 获取intent传递的数据
	 */
	private void initData() {
		try {
			mOrderId = getIntent().getStringExtra(INTENT_KEY_ORDER_ID);
			mOrderNum = getIntent().getStringExtra(INTENT_KEY_ORDER_NUM);
			mOrderPrice = Float.parseFloat(getIntent().getStringExtra(INTENT_KEY_ORDER_PRICE));
			if(!StringUtils.isEmpty(getIntent().getStringExtra(INTENT_KEY_ORDER_SERVICE_CARD_PRICE))) {
				mOrderServiceCardPrice =  Float.parseFloat(getIntent().getStringExtra(INTENT_KEY_ORDER_SERVICE_CARD_PRICE));
			}
		}catch (NumberFormatException e) {
			e.printStackTrace();
		}catch (NullPointerException e) {
			e.printStackTrace();
		}
	}
	
	/**
	 * 初始化组件
	 */
	private void initView() {

		//标题
		mLeftTv = (TextView) findViewById(R.id.left_ib);
		mMiddleTitleTv = (TextView) findViewById(R.id.middle_title_tv);
		mRightTv = (TextView) findViewById(R.id.right_ib);
		
		mLeftTv.setOnClickListener(new OnClickListener() {
			@Override
			public void onClick(View arg0) {
				Log.d(TAG, "mLeftTv click");
				AppManager.getAppManager().finishActivity();
			}
		});
		mMiddleTitleTv.setText("在线支付");
		mRightTv.setVisibility(View.GONE);
		
		//支付金额
		mPayOrderPriceTv = (TextView) findViewById(R.id.pay_order_price_tv);
		mPayOrderPriceTv.setText(MathUtil.priceForAppWithSign(mOrderPrice) + "元");
		
		//支付订单号
		mPayOrderNumTv = (TextView) findViewById(R.id.pay_order_num_tv);
		mPayOrderNumTv.setText(mOrderNum);
		
		//支付方式
		mPaywayServiceCardLayout = (LinearLayout) findViewById(R.id.payway_serviceCard);
		mPaywayAlipayLayout = (LinearLayout) findViewById(R.id.payway_zfb_android);
		mPaywayWXLayout = (LinearLayout) findViewById(R.id.payway_wx);
		mPaywayYLLayout = (LinearLayout) findViewById(R.id.payway_yl);
		
		mPaywayServiceCardLayout.setOnClickListener(this);
		mPaywayAlipayLayout.setOnClickListener(this);
		mPaywayWXLayout.setOnClickListener(this);
		mPaywayYLLayout.setOnClickListener(this);
		
		//便民卡支付金额信息
		mServiceCardInfoTv = (TextView) findViewById(R.id.serviceCard_info);
		if (AppContext.mUserInfo != null && AppContext.mUserInfo.getBDStatus() == 1) {
			if (mOrderServiceCardPrice > 0 && mOrderServiceCardPrice < mOrderPrice) {
				mServiceCardInfoTv.setText("使用服务卡支付价格为" + MathUtil.priceForAppWithSign(mOrderServiceCardPrice) + "元");
			}
		}
	}

	@Override
	public void onClick(View v) {
		// 如果金额小于等于0,不进入支付
		if (0 >= mOrderPrice) 
		{
			BaseHelper.showDialog(CommitOrderActivityNew.this, "提示", "支付金额错误，请确认！", R.drawable.infoicon);
			return;
		}
		switch (v.getId()) {
		//便民服务卡
		case R.id.payway_serviceCard:
		   mCurPayWay = PAYWAY_SERVICE_CARD;
		   if (AppContext.mUserInfo.hasBoundServiceCard()) 
		   {
			  showServiceCardPayDialog();
           } 
		   else 
		   {
              UIHelper.showToast("您还没绑定便民服务卡");
           } 
			break;
		//支付宝
		case R.id.payway_zfb_android:
			mCurPayWay = PAYWAY_ALIPAY;
			getChargeData(mOrderNum, CHANNEL_PAYWAY_ALIPAY);
			break;
		//微信
		case R.id.payway_wx:
			mCurPayWay = PAYWAY_WX;
			getChargeData(mOrderNum, CHANNEL_PAYWAY_WX);
			break;
		//银联
		case R.id.payway_yl:
			mCurPayWay = PAYWAY_YL;
			getChargeData(mOrderNum, CHANNEL_PAYWAY_YL);
			break;

		default:
			break;
		}
	}
	
	/**
	 * 获取Ping++支付charge对象
	 */
	private void getChargeData(String orderCode, String payChannel) {
		RequstClient.getChargeData(orderCode, payChannel, new CustomResponseHandler(this) {
			@Override
			public void onSuccess(int statusCode, String content) {
				super.onSuccess(statusCode, content);
				
				int type = JSONParseUtils.getInt(content, "type");
				String msg = JSONParseUtils.getString(content, "msg");
				if(type == 1) {
					//ping++支付对象
					String chargeData = JSONParseUtils.getString(content, "charge");
					startPay(chargeData);
				}
				else {
					UIHelper.showToast(msg);
				}
			}
		});
	}
	
	/**
	 * 启动Ping++支付
	 * @param data 支付参数json
	 */
	private void startPay(String data) {
		Log.d(TAG, "startPay : data = " + data);
		Intent intent = new Intent(CommitOrderActivityNew.this, PaymentActivity.class);
        intent.putExtra(PaymentActivity.EXTRA_CHARGE, data);
        startActivityForResult(intent, REQUEST_CODE_PAYMENT);
	}
	
	/**
	 * onActivityResult 获得支付结果，如果支付成功，服务器会收到ping++ 服务器发送的异步通知
	 * 最终支付成功根据异步通知为准
	 */
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
    	Log.d(TAG, "onActivityResult : requestCode = " + requestCode + " resultCode = " + resultCode);
        //支付页面返回处理
        if (requestCode == REQUEST_CODE_PAYMENT) {
            if (resultCode == Activity.RESULT_OK) {
            	/* 处理返回值
                 * "success" - payment succeed
                 * "fail"    - payment failed
                 * "cancel"  - user canceld
                 * "invalid" - payment plugin not installed
                 */
                String result = data.getExtras().getString("pay_result");
                String errorMsg = data.getExtras().getString("error_msg"); // 错误信息
                String extraMsg = data.getExtras().getString("extra_msg"); // 错误信息
                Log.d(TAG, "onActivityResult : result = " + result);
                Log.d(TAG, "onActivityResult : errorMsg = " + errorMsg);
                Log.d(TAG, "onActivityResult : extraMsg = " + extraMsg);
                
                switch (result) {
				case "success":
					goToPayResult(PaymentResultActivity.PAYMENT_SUCCESS, mCurPayWay, mOrderId, mOrderNum);
					break;
				case "fail":
					goToPayResult(PaymentResultActivity.PAYMENT_FAIL, mCurPayWay, mOrderId, mOrderNum);
					break;
				case "cancel":
					goToPayResult(PaymentResultActivity.PAYMENT_FAIL, mCurPayWay, mOrderId, mOrderNum);
					break;
				case "invalid":
					if(mCurPayWay == PAYWAY_WX) {
						UIHelper.showToast("请安装微信客户端！");
						return;
					}
					goToPayResult(PaymentResultActivity.PAYMENT_FAIL, mCurPayWay, mOrderId, mOrderNum);
					break;
				default:
					break;
				}
                
            }
        }
    }
    
    /**
     * 便民服务卡支付对话框
     * 输入便民服务卡密码确定支付/取消支付
     */
    private void showServiceCardPayDialog() {
		View mView = LayoutInflater.from(mContext).inflate(R.layout.service_card_dialog, null);
		mServiceCardDialog = new Dialog(mContext, R.style.dialog);
		TextView mTitleTv = (TextView) mView.findViewById(R.id.com_tip_tv);
		mTitleTv.setText("确认支付？");
		//密码输入框
		final EditText mPwdEdt = (EditText) mView.findViewById(R.id.com_message_tv);
		//确认
		Button mYesBtn = (Button) mView.findViewById(R.id.com_ok_btn);
		//取消
		Button mCancleBtn = (Button) mView.findViewById(R.id.com_cancel_btn);
		mYesBtn.setText("确定支付");
		mCancleBtn.setText("取消支付");
		mYesBtn.setOnClickListener(new OnClickListener() {

			@Override
			public void onClick(View v) {
				mServiceCardDialog.dismiss();
				String password = mPwdEdt.getText().toString();
				if (StringUtils.isBlank(password)) {
					UIHelper.showToast("请输入密码");
					return;
				}
				startServiceCardPay(password);
			}
		});
		mCancleBtn.setOnClickListener(new OnClickListener() {
			
			@Override
			public void onClick(View v) {
				mServiceCardDialog.dismiss();
			}
		});
		mServiceCardDialog.setContentView(mView);
		mServiceCardDialog.setCanceledOnTouchOutside(true);
		mServiceCardDialog.setCancelable(true);
		mServiceCardDialog.show();
	}
    
    /**
     * 便民服务卡支付失败对话框
     */
    private void showServiceCardFailDialog(String msg) {
		View mView = LayoutInflater.from(mContext).inflate(R.layout.service_card_pay_fail_dialog, null);
		mServiceCardDialog = new Dialog(mContext, R.style.dialog);
		//消息提示
		TextView mMessageTv = (TextView) mView.findViewById(R.id.com_message_tv);
		mMessageTv.setText(msg);
		//选择其他支付方式
		Button mOtherPayBtn = (Button) mView.findViewById(R.id.com_ok_btn);
		//充值便民服务卡
		Button mRechargeBtn = (Button) mView.findViewById(R.id.com_cancel_btn);
		mOtherPayBtn.setOnClickListener(new OnClickListener() {

			@Override
			public void onClick(View v) {
				mServiceCardDialog.dismiss();
			}
		});
		mRechargeBtn.setOnClickListener(new OnClickListener() {

			@Override
			public void onClick(View v) {
				mServiceCardDialog.dismiss();
				Intent intent = new Intent();
				intent.setClass(mContext, RechargeServiceCard.class);
				mContext.startActivity(intent);
				AppManager.getAppManager().finishActivity();
			}
		});
		mServiceCardDialog.setContentView(mView);
		mServiceCardDialog.setCanceledOnTouchOutside(true);
		mServiceCardDialog.setCancelable(true);
		mServiceCardDialog.show();
	}
    
    /**
     * 便民服务卡支付
     * @param password 便民服务卡密码
     */
    private void startServiceCardPay(String password) {
		UserInfo mUsrInfo = AppContext.mUserInfo;
		CustomResponseHandler handler = new CustomResponseHandler(this, true) {
			@Override
			public void onRefreshData(String content) {
				super.onRefreshData(content);
				Gson gson = new Gson();
				BaseBean bean = gson.fromJson(content, BaseBean.class);
				//支付成功
				if (bean.type > 0) {
					goToPayResult(PaymentResultActivity.PAYMENT_SUCCESS, mCurPayWay, mOrderId, mOrderNum);
				} 
				//支付失败
				else {
					showServiceCardFailDialog(bean.msg);
				}
			}
		};
		//便民卡支付价格
		String money;
		if (mOrderServiceCardPrice > 0) {
			money = MathUtil.keep2decimal(mOrderServiceCardPrice);
		} else {
			money = MathUtil.keep2decimal(mOrderPrice);
		}
		RequstClient.appCardRedeem(handler, mUsrInfo.userId, mUsrInfo.cardNum, password, money, mOrderNum, mUsrInfo.token, mOrderId);
	}
    
  
    /**
     * 跳转支付结果页面
     * @param paymentResult  PAYMENT_SUCCESS:成功  PAYMENT_FAIL:支付失败
     * @param payWay     当前选折的支付方式 
     * @param orderId    订单id
     * @param orderNum   订单编号
     */
	private void goToPayResult(int paymentResult, int payWay, String orderId, String orderNum) {
		Intent i = new Intent();
		i.setClass(CommitOrderActivityNew.this, PaymentResultActivity.class);
		i.putExtra(PaymentResultActivity.INTENT_KEY_PAYMENT_RESULT, paymentResult);
		i.putExtra(PaymentResultActivity.INTENT_KEY_PAY_WAY, payWay);
		i.putExtra(PaymentResultActivity.INTENT_KEY_ORDER_ID, orderId);
		i.putExtra(PaymentResultActivity.INTENT_KEY_ORDER_NUM, orderNum);
		startActivity(i);
		//CommitOrderActivityNew.this.finish();
	}

}
